package com.dao;

import java.sql.SQLException;
import java.util.List;

import com.db.JdbcTemplate;
import com.entity.Users;
import com.mapping.UsersMapping;

public class UsersDAO {
	private static JdbcTemplate jdbc = new JdbcTemplate();

	/**
	 * 新增
	 * 
	 * @param 
	 * @return
	 */
	public boolean save(Users users) {
		int r = 0;
		String sql = "insert into users(user_id,user_name,user_password)values(users_seq.nextval,?,?)";
		Object[] values = new Object[] { users.getUser_name(),
				users.getUser_password() };
		r = jdbc.update(sql, values);
		return (r == 1);
	}

	/**
	 * 删除
	 * 
	 * @param id
	 * @return
	 */
	public boolean delectById(int id) {
		String sql = "delete from users where user_id=" + id;
		int r = 0;
		r = jdbc.update(sql);
		return (r == 1);
	}

	public boolean delectByName(String name) {
		String sql = "delete from users where user_name=" + "'" + name + "'";
		int r = 0;
		r = jdbc.update(sql);
		return (r == 1);
	}

	/**
	 * 修改
	 * 
	 * @param bookType
	 * @return
	 */
	public boolean updateById(Users users) {
		String sql = "update users set user_name=?,user_password=? " + "where "
				+ "user_id=?";
		Object[] values = new Object[] { users.getUser_name(),
				users.getUser_password(), users.getUser_id() };
		int r = 0;
		r = jdbc.update(sql, values);
		return (r == 1);
	}

	public boolean updateByName(Users users) {
		String sql = "update users set user_password=? " + "where "
				+ "user_name=?";
		Object[] values = new Object[] { users.getUser_password(),
				users.getUser_name() };
		int r = 0;
		r = jdbc.update(sql, values);
		return (r == 1);
	}

	/**
	 * 查询全部
	 * 
	 * @param booktype
	 * @return
	 */
	public List<Users> findAll() {
		String sql = "select " + "user_id,user_name,user_password " + "from "
				+ "users order by user_id asc";
		List<Users> users = null;
		users = jdbc.query(sql, new UsersMapping());
		return users;
	}

	/**
	 * 查询一条id
	 * 
	 * @param id
	 * @return
	 */
	public Users findById(int id) {
		String sql = "select" + " user_id,user_name,user_password  " + "from  "
				+ "users where user_id=" + id;
		Users users = null;
		List entity = jdbc.query(sql, new UsersMapping());
		users = (Users) entity.get(0);
		return users;
	}

	/**
	 * 查询一条name
	 * 
	 * @param name
	 * @return
	 */
	public Users findByName(String name) {
		String sql = "select " + "user_id,user_name,user_password " + "from "
				+ "users where user_name=" + "'" + name + "'";
		Users users = null;
		List entity = jdbc.query(sql, new UsersMapping());
		users = (Users) entity.get(0);
		return users;
	}

}
